﻿using DHQGHN.Common;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.DAL.BO.DHQG;
using DHQGHN.DAL.Common;
using DHQGHN.DAL.Models.DHQG;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM2.Models.DHQG;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace DHQGHN.PM2.Controllers
{
    public class NguoiDungController : BaseController
    {
        private NguoiDungBO _sqlBO;
        public ActionResult Index(NguoiDungModel a = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", string curentID = "")
        {
            SetActiveMenu("/NguoiDung/Index");
            //ViewBag.ActiveMenus = ViewBag.ActiveMenus == null ? new System.Collections.Hashtable() : ViewBag.ActiveMenus;

            //string strInputMenuUrl = "/NguoiDung/Index";
            //List<DHQGHN.PM2.Models.MenuModel> listMenu = Session["MenuList"] as List<DHQGHN.PM2.Models.MenuModel>;
            //if (listMenu.Count > 0)
            //{
            //    for (int i = 0; i < listMenu.Count; i++)
            //    {
            //        if (listMenu[i].MenuUrl.ToUpper().Equals(strInputMenuUrl.ToUpper()))
            //        {
            //            ViewBag.ActiveMenus[listMenu[i].ParentMenuId] = "active";
            //            ViewBag.ActiveMenus[listMenu[i].MenuId] = "active";
            //            ViewBag.CurrentMenuName = listMenu[i].MenuName;
            //        }
            //    }
            //}
            ViewBag.DanhSachDonVi = GetListDonVi();

            if (a == null) { a = new NguoiDungModel(); }
            a.DON_VI_ID = 0; // GetDonViId();
            a.DELETED = 2;            

            var model = Search(a, pageIndex, curentID, false);
            return View(model);
        }

        private List<SelectListItem> GetListDonVi()
        {
            DonViBO donViBO = new DonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            List<DAL.Models.DHQG.DonVi> danhSachDonVi = donViBO.GetAll();
            List<SelectListItem> listDonVi = new List<SelectListItem>();
            listDonVi.Add(new SelectListItem()
            {
                Value = "0",
                Text = "-- Chọn đơn vị --"
            });
            for(int i = 0;i< danhSachDonVi.Count;i++)
            {
                listDonVi.Add(new SelectListItem()
                {
                    Value = danhSachDonVi[i].DonViId.ToString(),
                    Text = danhSachDonVi[i].TenDonVi
                });
            }

            return listDonVi;
        }

        [HttpPost]
        public ActionResult CreatePopupUpdate(string id)
        {
            NguoiDungModel nguoiDungInfoPM2 = Session["PM2_NguoiDungInfo"] as NguoiDungModel;            
           
            NguoiDungModel model = null;
            int nhomDonViId = 0;
            if (!(String.IsNullOrEmpty(id) || String.IsNullOrWhiteSpace(id)))
            {
                _sqlBO = GetSqlBO();
                int nguoiDungId = 0;
                if (int.TryParse(id, out nguoiDungId))
                {
                    model = new NguoiDungModel(_sqlBO.GetById(nguoiDungId));
                    Session["UserBackup"] = model;
                    nhomDonViId = GetNhomDonViIdByDonViId(model.DON_VI_ID);
                }                
            }
            if (model == null)
            {
                model = new NguoiDungModel();
                model.DON_VI_ID = 0;
            }

            DonViBO _sqlDonViBO = new DonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            List<DonVi> danhSachDonViTheoNhom = _sqlDonViBO.GetAllDonViByNhom(nhomDonViId);
            List<SelectListItem> lstDonVi = new List<SelectListItem>();
            lstDonVi.Add(new SelectListItem
            {
                Text = "Chọn đơn vị",
                Value = ""
            });
            for (int i = 0; i < danhSachDonViTheoNhom.Count; i++)
            {
                lstDonVi.Add(new SelectListItem
                {
                    Text = danhSachDonViTheoNhom[i].TenDonVi,
                    Value = danhSachDonViTheoNhom[i].DonViId.ToString(),
                    Selected = danhSachDonViTheoNhom[i].DonViId == model.DON_VI_ID ? true: false
                });
            }
            
            ViewBag.lstNhomDonVi = GetListNhomDonVi(nhomDonViId);
            ViewBag.lstDonVi = lstDonVi;
            ViewBag.NhomDonViId = nhomDonViId.ToString();

            if (Request.IsAjaxRequest())
            {
                return PartialView(model);
            }
            return View(model);
        }

        private int GetNhomDonViIdByDonViId(int donViId)
        {
            NhomDonViBO _sqlNhomDVBO = new NhomDonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            List<NhomDonVi> danhSachNhomDonVi = new List<NhomDonVi>();
            if (donViId > 0)
            {
                danhSachNhomDonVi = _sqlNhomDVBO.GetAllNhomByDonViID(donViId);
            }
            int nhomDonViId = 0;
            for (int i = 0; i < danhSachNhomDonVi.Count; i++)
            {
                if (danhSachNhomDonVi[i].IS_CHECKED == 1)
                {
                    nhomDonViId = danhSachNhomDonVi[i].NhomDonViId;
                    break;
                }
            }

            return nhomDonViId;
        }

        private List<SelectListItem> GetListNhomDonVi(int nhomDonViId)
        {
            NhomDonViBO _sqlNhomDVBO = new NhomDonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            
            List<NhomDonVi> items = _sqlNhomDVBO.GetAll();            
            List<SelectListItem> lstNhomDonVi = new List<SelectListItem>();
            lstNhomDonVi.Add(new SelectListItem
            {
                Text = "Chọn nhóm đơn vị",
                Value = ""
            });
            for (int i = 0; i < items.Count; i++)
            {
                lstNhomDonVi.Add(new SelectListItem
                {
                    Text = items[i].TenNhomDonVi,
                    Value = items[i].NhomDonViId.ToString(),
                    Selected = (nhomDonViId == items[i].NhomDonViId ? true: false)
                });
            }

            return lstNhomDonVi;
        }

        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult ActionSave(NguoiDungModel model)
        {
            if (Request.IsAjaxRequest())
            {
                _sqlBO = GetSqlBO();
                //model.DON_VI_ID = GetDonViId();
                bool result = _sqlBO.Save(model.ToDALModel());
                if (result)
                {
                    if (model.NGUOI_DUNG_ID > 0)
                    {
                        NguoiDungModel oldUser = (Session["UserBackup"] != null ?
                            (NguoiDungModel)Session["UserBackup"] : (new NguoiDungModel()));
                        USER_GROUP_CREATE data = GetUserData(model, oldUser.TAI_KHOAN);
                        bool updateResult = UpdateUser(data);
                        if (updateResult)
                        {
                            return Json(JsonResponse.Json200("Cập nhật thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình cập nhật sang hệ quản trị!"));
                        }
                    }
                    else
                    {
                        string message = "Thêm mới thành công!";
                        try
                        {
                            //string maDv = string.Empty;
                            int intDonViID = 0;
                            //USER_GROUP_CREATE data = GetData(maDv, model);
                            List<USER_GROUP_CREATE> listData = GetListData(intDonViID, model);
                            bool isOK = true;
                            string strErrorMessage = string.Empty;
                            if (listData.Count > 0)
                            {
                                for (int i = 0; i < listData.Count; i++)
                                {
                                    var resultMessage = RegisterUser(listData[i]);
                                    if (resultMessage.ErrorCode != 200)
                                    {
                                        isOK = false;
                                        strErrorMessage = resultMessage.ErrorMessage;
                                    }
                                }
                            }

                            //var resultMessage = RegisterUser(data);
                            //if (resultMessage.ErrorCode != 200)
                            if (isOK == false)
                            {
                                //message = resultMessage.ErrorMessage;
                                message = strErrorMessage;
                            }
                        }
                        catch
                        {
                            throw;
                        }
                        return Json(JsonResponse.Json200(message));
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        [AjaxValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult ActionDelete(int[] id, string[] userName)
        { 
            if (Request.IsAjaxRequest())
            {
                _sqlBO = GetSqlBO();               
               
                bool result = _sqlBO.Delete(id);
                if (result)
                {
                    bool deleteResult = deleteUser(userName, DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE);
                    if(deleteResult)
                    {
                        Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý trên hệ quản trị!"));
                    }
                    return Json(JsonResponse.Json200("Xóa thành công"));
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        [HttpPost]
        public ActionResult ActionSearch(NguoiDungModel model = null, int pageIndex = 0, string sort = "CertificationId", string sortDir = "ASC", string currentId = "")
        {
            if (model == null)
            {
                model = new NguoiDungModel();
            }
            //model.DON_VI_ID = GetDonViId();
            var dataPaging = Search(model, pageIndex, currentId, false);
            return PartialView("~/Views/NguoiDung/_NguoiDungList.cshtml", dataPaging);
        }


        [AjaxValidateAntiForgeryToken]
        [HttpPost]
        public ActionResult Reactive(int nguoiDungId, string taiKhoan)
        {
            if (Request.IsAjaxRequest())
            {
                _sqlBO = new NguoiDungBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                UserBO userBO = new UserBO();
                bool result = _sqlBO.Reactive(nguoiDungId);
                if (result)
                {
                    bool reactiveResult = userBO.Reactive(taiKhoan, DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE);
                    if (reactiveResult)
                    {
                        return Json(JsonResponse.Json200("Khôi phục người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
                else
                {
                    return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                }
            }
            return null;
        }

        private DataPage<NguoiDungModel> Search(NguoiDungModel myModel, int pageIndex, string currentId, bool compareEqual)
        {
            _sqlBO = GetSqlBO();

            var DALModel = _sqlBO.GetListPaging(myModel.ToDALModel(), pageIndex, PageSize);
            var models = new DataPage<NguoiDungModel>();
            var lstItem = DALModel.Data;
            foreach (DHQGHN.DAL.Models.DHQG.NguoiDung nguoiDung in lstItem)
            {
                models.Data.Add(new NguoiDungModel(nguoiDung));
            }

            NguoiDungModel model = null;
            if (!String.IsNullOrEmpty(currentId) && models.Data.Count > 0)
            {
                model = models.Data.Find(user => user.NGUOI_DUNG_ID.Equals(currentId));
                models.CustomData = model;
            }
            else
            {
                models.CustomData = myModel;
            }
            if (models.Data.Count > 0)
            {
                //Tao component phan trang
                var pagNative = new Pagination
                {
                    ActionName = "ActionSearch",
                    ModelName = "NguoiDung",
                    CurrentPage = pageIndex,
                    InputSearchId = "",
                    TagetReLoadId = "certification-list",

                };
                pagNative.TotalRows = models.Data[0].RECORD_COUNT;
                pagNative.CurrentRow = models.Data.Count;
                ViewBag.Pagination = pagNative;
            }
            return models;
        }

        public JsonResult CheckUserNameExist(string TAI_KHOAN, int NGUOI_DUNG_ID)
        {
            try
            {
                _sqlBO = GetSqlBO();
                bool result = _sqlBO.CheckUserNameExist(TAI_KHOAN);
                if (NGUOI_DUNG_ID > 0 && result)
                {
                    return Json(result);
                }
                // result: true: chua ton tai, nguoc lai da ton tai
                return Json(!result);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private USER_GROUP_CREATE RegisterUser(USER_GROUP_CREATE user)
        {
            try
            {
                USER_GROUP_CREATE ret = user;
                if (String.IsNullOrWhiteSpace(ret.UserName))
                {
                    ret.ErrorCode = 1;
                    ret.ErrorMessage = "Xảy ra lỗi. Tên đăng nhập không được rỗng!";
                    return ret;
                }

                ret.ErrorCode = 200;
                var userBO = new UserBO();
                bool result = userBO.RegisterUser(ret);

                if (ret.ErrorCode == 200 && result)
                {
                    ret.ErrorMessage = "SUCCESS";

                    //UserInGroupBO userInGroupBO = new UserInGroupBO();
                    //bool flag = userInGroupBO.AddUserIntoGroup(ret);
                    //if (flag == true)
                    //{
                    //    ret.ErrorMessage = "SUCCESS";
                    //}
                    //else
                    //{
                    //    ret.ErrorCode = -1;
                    //    ret.ErrorMessage = "Xảy ra lỗi trong khi thêm người dùng vào nhóm";
                    //}
                }
                else
                {
                    ret.ErrorCode = 400;
                    ret.ErrorMessage = "Xảy ra lỗi khi thêm người dùng vào hệ thống";
                }

                return ret;
            }
            catch
            {
                throw;
            }
        }

        private USER_GROUP_CREATE GetData(string maDonVi, NguoiDungModel model)
        {
            USER_GROUP_CREATE item = new USER_GROUP_CREATE();
            item.Password = "123456qR@";
            item.FullName = model.HO_VA_TEN;
            item.IsActive = 1;
            item.AppCode = DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE;
            item.Type = "B";
            item.UserName = model.TAI_KHOAN;
            //if (maDonVi == "KHTC")
            //{
            //    item.GroupCode = "KH";
            //}
            //else if (maDonVi == "BANTNXH")
            //{
            //    item.GroupCode = "DV";
            //}
            //else if (maDonVi == "BANDT")
            //{
            //    item.GroupCode = "BA";
            //}

            item.GroupCode = "DV";

            return item;
        }
        //phunx1, 20160529: lay danh sach data
        private List<USER_GROUP_CREATE> GetListData(int intDonViID, NguoiDungModel model)
        {
            //List<USER_GROUP_CREATE> lstItem = new List<USER_GROUP_CREATE>();
            //DonViBO donViBO = new DonViBO(DHQGHN.DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
            //GroupBO groupBO = new GroupBO();
            //List<DonVi> lstGroupID = donViBO.GetGroupByDonViID(intDonViID);
            //if (lstGroupID.Count > 0)
            //{
            //    for (int i = 0; i < lstGroupID.Count; i++)
            //    {
            //        USER_GROUP_CREATE item = new USER_GROUP_CREATE();
            //        item.Password = "123456qR@";
            //        item.FullName = model.HO_VA_TEN;
            //        item.IsActive = 1;
            //        item.AppCode = DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE;
            //        item.Type = "B";
            //        item.UserName = model.TAI_KHOAN;
            //        //item.GroupCode = "DV";
            //        item.GroupCode = groupBO.GetGroupCodeByGroupId(lstGroupID[i].NhomDonViId);

            //        lstItem.Add(item);
            //    }
            //}

            List<USER_GROUP_CREATE> lstItem = new List<USER_GROUP_CREATE>();           
            
            
            
            
                
                {
                    USER_GROUP_CREATE item = new USER_GROUP_CREATE();
                    item.Password = "123456qR@";
                    item.FullName = model.HO_VA_TEN;
                    item.IsActive = 1;
                    item.AppCode = DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE;
                    item.Type = "B";
                    item.UserName = model.TAI_KHOAN;
                    lstItem.Add(item);
                }
            


                
            //if (maDonVi == "KHTC")
            //{
            //    item.GroupCode = "KH";
            //}
            //else if (maDonVi == "BANTNXH")
            //{
            //    item.GroupCode = "DV";
            //}
            //else if (maDonVi == "BANDT")
            //{
            //    item.GroupCode = "BA";
            //}

            return lstItem;
        }

        public bool UpdateUser(USER_GROUP_CREATE user)
        {
            try
            {
                var userBO = new UserBO();
                return userBO.UpdateUser_DHQG(user);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private USER_GROUP_CREATE GetUserData(NguoiDungModel model, string userNameOld)
        {
            USER_GROUP_CREATE data = new USER_GROUP_CREATE();
            data.AppCode = DHQGHN.MVC.Controllers.CommonData.KH_DHQGHN_CODE;
            data.UserName_Old = userNameOld;
            data.Email = string.Empty;
            data.FullName = model.HO_VA_TEN;
            data.UserName = model.TAI_KHOAN;

            return data;
        }

        public bool deleteUser(string[] userName, string appCode)
        {
            try
            {
                UserBO userBO = new UserBO(); 
                bool ret = userBO.deleteUser(userName, appCode);
                return ret;

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        [HttpPost]
        public JsonResult GetDonViByNhom(string strNhomDonViID)
        {
            try
            {
                int intNhomDonViID = 0;
                DonViBO _sqlDonViBO = new DonViBO(DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);
                if (!string.IsNullOrEmpty(strNhomDonViID))
                {
                    intNhomDonViID = int.Parse(strNhomDonViID);
                }

                List<DonVi> temp = _sqlDonViBO.GetAllDonViByNhom(intNhomDonViID);
                List<SelectListItem> lstDonVi = new List<SelectListItem>();
                lstDonVi.Add(new SelectListItem
                {
                    Text = "Chọn đơn vị",
                    Value = ""
                });
                for (int i = 0; i < temp.Count; i++)
                {
                    lstDonVi.Add(new SelectListItem
                    {
                        Text = temp[i].TenDonVi,
                        Value = temp[i].DonViId.ToString()
                    });
                }

                return Json(lstDonVi, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                //logger.Error(ex.ToString());
                throw;
                //return null;
            }
        }

        private int GetDonViId()
        {
            int donViId = 0;
            if (Session["NguoiDungInfo"] != null)
            {
                NguoiDungModel userInfo = (NguoiDungModel)Session["NguoiDungInfo"];
                List<DHQGHN.PM2.Models.DonViModel> listDonVi = userInfo.listDonVi;
                if (listDonVi != null)
                {
                    donViId = listDonVi.Count > 0 ? listDonVi[0].DonViId : 0;
                }
            }

            return donViId;
        }

        private NguoiDungBO GetSqlBO()
        {
            return new NguoiDungBO(DHQGHN.DAL.Common.ConnectionUtil.DHQGHN_HTTTKH_CONNECTIONSTRING);

        }
    }
}